const { Sequelize, DataTypes } = require('sequelize');
const config = require('./config/config.json').development;

// 创建 Sequelize 实例
const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: config.dialect,
  port: config.port,
});

// 定义模型
const SalesOrder = sequelize.define('sales_order', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  platformOrderId: {
    type: DataTypes.STRING,
    allowNull: true
  },
  customerId: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  orderAmount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true
  },
  orderStatus: {
    type: DataTypes.STRING,
    allowNull: true
  },
  orderDate: {
    type: DataTypes.DATE,
    allowNull: true
  },
  platformSource: {
    type: DataTypes.STRING,
    allowNull: true
  },
  invoiceStatus: {
    type: DataTypes.STRING,
    allowNull: true
  },
  invoiceDate: {
    type: DataTypes.DATE,
    allowNull: true
  },
  responsibleSalesman: {
    type: DataTypes.STRING,
    allowNull: true
  },
  isGift: {
    type: DataTypes.BOOLEAN,
    allowNull: true
  },
  collectionStatus: {
    type: DataTypes.STRING,
    allowNull: true
  },
  collectionCount: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  lastCollectionDate: {
    type: DataTypes.DATE,
    allowNull: true
  },
  lastCollectionResult: {
    type: DataTypes.STRING,
    allowNull: true
  },
  nextFollowupDate: {
    type: DataTypes.DATE,
    allowNull: true
  },
  orderNo: {
    type: DataTypes.STRING,
    allowNull: true
  },
  organizationId: {
    type: DataTypes.INTEGER,
    allowNull: true
  }
}, {
  tableName: 'sales_orders',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

const SalesOrderItem = sequelize.define('sales_order_item', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  orderId: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  productId: {
    type: DataTypes.STRING,
    allowNull: true
  },
  productName: {
    type: DataTypes.STRING,
    allowNull: true
  },
  specification: {
    type: DataTypes.STRING,
    allowNull: true
  },
  quantity: {
    type: DataTypes.INTEGER,
    allowNull: true
  },
  unit: {
    type: DataTypes.STRING,
    allowNull: true
  },
  unitPrice: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true
  },
  remark: {
    type: DataTypes.STRING,
    allowNull: true
  }
}, {
  tableName: 'sales_order_items',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

async function checkDatabase() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');

    // 查询销售订单数量
    const orderCount = await SalesOrder.count();
    console.log(`销售订单表中有 ${orderCount} 条记录`);

    // 查询销售订单项数量
    const orderItemCount = await SalesOrderItem.count();
    console.log(`销售订单项表中有 ${orderItemCount} 条记录`);

    // 如果有订单数据，显示前几条
    if (orderCount > 0) {
      const orders = await SalesOrder.findAll({
        limit: 3,
        order: [['created_at', 'DESC']]
      });
      console.log('最近的订单:');
      orders.forEach(order => {
        console.log(`- 订单ID: ${order.platformOrderId}, 金额: ${order.orderAmount}, 状态: ${order.orderStatus}`);
      });
    }

    // 查询插件数据批次表
    const [batchResults] = await sequelize.query(
      'SELECT COUNT(*) as count FROM plugin_data_batches'
    );
    console.log(`插件数据批次表中有 ${batchResults[0].count} 条记录`);

    // 查询插件数据项表
    const [itemResults] = await sequelize.query(
      'SELECT COUNT(*) as count FROM plugin_data_items'
    );
    console.log(`插件数据项表中有 ${itemResults[0].count} 条记录`);

    // 查看最新的批次数据
    if (batchResults[0].count > 0) {
      const [latestBatches] = await sequelize.query(
        'SELECT * FROM plugin_data_batches ORDER BY created_at DESC LIMIT 3'
      );
      console.log('最新的批次数据:');
      latestBatches.forEach(batch => {
        console.log(`- 批次ID: ${batch.batch_id}, 类型: ${batch.data_type}, 状态: ${batch.status}`);
      });
    }

  } catch (error) {
    console.error('检查数据库时出错:', error);
  } finally {
    await sequelize.close();
  }
}

checkDatabase();